<?php

namespace App\Http\Logic\Admin;

use App;
use App\Common\Status;
use \App\Models\Job;
use App\Models\Note;
use \App\Models\RecruitPositionCategory;
use \App\Models\Business;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Qiniu\Auth;
use Illuminate\Support\Facades\Storage;
use TCPDF;

class JobLogic
{
    //    use App\Http\Logic\PC\TTUsersLogic2 {
    //        App\Http\Logic\PC\TTUsersLogic2::AgetUserInfo as   traitMethod;
    //    }
    use App\Http\Logic\NoteOtherLogic;

    /**
     * @param $params
     * @param $pageSize
     * @param $page
     * @return array
     */
    public static function getJobList($params, $pageSize, $page)
    {
        $where[] = ['a.is_deleted', '=', Status::NOT_DELETE];

        if (isset($params['work_exp']) && $params['work_exp']) {
            $where[] = ['a.work_exp', '=', $params['work_exp']];
        }
        if (isset($params['st_dt']) && $params['st_dt']) {
            $where[] = ['a.created_at', '>=', strtotime($params['st_dt'])];
        }
        if (isset($params['en_dt']) && $params['en_dt']) {
            $where[] = ['a.created_at', '<=', strtotime($params['en_dt'])];
        }
        if (isset($params['city']) && $params['city']) {
            $where[] = ['a.city', '=', $params['city']];
        }
        if (isset($params['education']) && $params['education']) {
            $where[] = ['a.education', '=', $params['education']];
        }

        if (isset($params['status']) && $params['status']) {
            $where[] = ['a.status', '=', $params['status']];
        }

        if (isset($params['hot']) && $params['hot']) {
            $where[] = ['a.hot', '=', $params['hot']];
        }

        $cateIds = $busIds = [];

        # 企业
        if (isset($params['business_name']) && $params['business_name']) {
            $busIds = Business::select(["id"])
                ->where("name", 'like', '%' . $params['business_name'] . '%')
                ->get();
            //                ->toSql();
            if (!$busIds->isEmpty()) {
                $busIds = $busIds->pluck("id")->toArray();
            }
        }

        # 分类
        if (isset($params['position_custom_name']) && $params['position_custom_name']) {
            $where[] = ['a.position_custom_name', 'like', '%' . $params['position_custom_name'] . '%'];

        }

        $field = [
            "a.id",
            "a.business_id",
            "c.name as business_name",
            "a.position_custom_name",
            "a.position_category_child_id",
            //            "b.name as position_category_child_name",
            "a.work_exp",
            "a.education",
            "a.salary1",
            "a.salary2",
            "a.salary_month",
            "a.welfare",
            "a.city",
            "a.area",
            "a.email",
            "a.release",
            "a.release_job",
            "a.job_type",
            "a.release_mobile",
            "a.describe",
            "a.hot",
            "a.show",
            "a.created_at",
            "a.status"
        ];
        $data  = DB::table('recruit_job as a')
            //            ->leftJoin('recruit_position_category as b', "a.position_category_child_id", "=", "b.id")
            ->select($field)
            ->leftJoin('recruit_business as c', "a.business_id", "=", "c.id")
            ->where($where)
            ->when($busIds, function ($query, $busIds) {
                return $query->whereIn('business_id', $busIds);
            })
            ->when($cateIds, function ($query, $cateIds) {
                return $query->whereIn('position_category_child_id', $cateIds);
            })
            ->orderBy("a.created_at", "desc")
            ->offset($pageSize * ($page - 1))
            ->limit($pageSize)
            ->get();
        $count = self::getCount($where, $busIds, $cateIds);

        $data = self::getDataInfo($data);
        return ['list' => $data, 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];

    }

    private static function getCount($where, $busIds, $cateIds)
    {
        return DB::table('recruit_job as a')
            ->leftJoin('recruit_position_category as b', "a.position_category_child_id", "=", "b.id")
            ->leftJoin('recruit_business as c', "a.business_id", "=", "c.id")
            ->where($where)
            ->when($busIds, function ($query, $busIds) {
                return $query->whereIn('business_id', $busIds);
            })
            ->when($cateIds, function ($query, $cateIds) {
                return $query->whereIn('position_category_child_id', $cateIds);
            })
            ->count();
    }


    /**
     * @param $params
     * @return mixed
     * @throws \Exception
     */
    public static function createJob($params)
    {
        if (count($params['welfare']) > 0) {
            $params['welfare'] = implode(',', $params['welfare']);
        } else {
            unset($params['welfare']);
        }

        $connection = DB::connection('mysql');

        $connection->beginTransaction();
        try {
            if (isset($params['id']) && $params['id']) {
                $id = $params['id'];

                $params['updated_at'] = time();

                unset($params['id']);

                //                self::setCityUse($id, $params['city'], $params['area']);

                Job::where('id', $id)->update($params);

                $connection->commit();

                return true;
            }

            $params['created_at'] = time();

            $params['creator_id'] = Helper::adminById();

            $id = Job::insertGetId($params);

            //            self::setCityUse($id, $params['city'], $params['area'], 2);

            $connection->commit();

            return $id;

        } catch (\Exception $exception) {
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }
    }


    /**
     * @param $id
     * @param $city
     * @param $area
     * @param int $ct
     */
    private static function setCityUse($id, $city, $area, $ct = 1)
    {
        # 修改
        $job = Job::find($id);
        if ($ct == 1) {
            if ($job) {
                if (($job->city != $city) && ($job->area != $area)) {
                    DB::table("recruit_city")->where("id", $job->city)->decrement('use');
                    DB::table("recruit_city")->where("id", $job->area)->decrement('use');
                } elseif (($job->city == $city) && ($job->area != $area)) {

                    # 城市相同 区县不同
                    DB::table("recruit_city")->where("id", $job->area)->decrement('use');
                }
            }
        } elseif ($ct == 9) {
            # 删除
            DB::table("recruit_city")->where("id", $job->city)->decrement('use');
            DB::table("recruit_city")->where("id", $job->area)->decrement('use');
        } elseif ($ct == 3) {
            # 停止
            DB::table("recruit_city")->where("id", $job->city)->decrement('use');
            DB::table("recruit_city")->where("id", $job->area)->decrement('use');
        } elseif ($ct == 2) {
            # 开启
            DB::table("recruit_city")->where("id", $job->city)->increment('use');
            DB::table("recruit_city")->where("id", $job->area)->increment('use');
        } else {

            # 新增
            DB::table("recruit_city")->where("id", $city)->increment('use');
            DB::table("recruit_city")->where("id", $area)->increment('use');
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public function getJobDtl($id)
    {
        $field = [
            "a.id as jid",
            "a.business_id",
            "c.name as business_name",
            "a.position_custom_name",
            "a.position_category_child_id",
            "b.name as position_category_child_name",
            "a.work_exp",
            "a.education",
            "a.salary1",
            "a.salary2",
            "a.salary_month",
            "a.welfare",
            "a.city",
            "a.area",
            "a.email",
            "a.release",
            "a.release_job",
            "a.job_type",
            "a.release_mobile",
            "a.describe",
            "a.hot",
            "a.show",
            "a.status"
        ];
        $data  = DB::table('recruit_job as a')
            ->leftJoin('recruit_position_category as b', "a.position_category_child_id", "=", "b.id")
            ->leftJoin('recruit_business as c', "a.business_id", "=", "c.id")
            ->select($field)
            ->where("a.id", $id)
            ->first();

        if ($data) {
            self::getDataInfo([$data]);
        }
        return $data;
    }


    /**
     * @param $id
     * @return mixed
     */
    public static function delJob($id)
    {
        $connection = DB::connection('mysql');
        $connection->beginTransaction();
        try {
            //            self::setCityUse($id, '', '', 9);
            Job::where('id', $id)->update(
                [
                    'is_deleted' => Status::DELETED,
                    'deleted_at' => time()
                ]
            );
            $connection->commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }
    }


    /**
     * @param $id
     * @param $type
     * @param $status
     * @return mixed
     */
    public static function setStatus($id, $type, $status)
    {
        $c = Job::select("hot", "show", "status")->find($id);
        if ($type == 1) {
            $hot = $c->hot == 1 ? 2 : 1;
            if ($c->hot == 2 && $hot) {
                $cun = Job::where("hot", 2)->count();

                if ($cun == 9) {
                    return ["status" => Status::ERROR, "msg" => "热门职位已达到上线！"];
                }
            }
            Job::where('id', $id)->update(['hot' => $hot, 'updated_at' => time()]);
            return ["status" => Status::SUCCESS, "msg" => ""];
        } elseif ($type == 2) {  # 招聘状态
            $connection = DB::connection('mysql');
            $connection->beginTransaction();
            try {
                //                self::setCityUse($id, '', '', $status);
                Job::where('id', $id)->update(['status' => $status, 'updated_at' => time()]);
                $connection->commit();
                return ["status" => Status::SUCCESS, "msg" => ""];

            } catch (\Exception $exception) {
                DB::rollBack();
                throw new \Exception($exception->getMessage());
            }
        }
    }


    /**
     * 匹配
     * @param $params
     * @throws \Exception
     */
    public static function autoMatch($params, $pageSize, $page)
    {
        $where = [['status', "=", 2], ['show', "=", 2], ['is_deleted', "=", Status::NOT_DELETE]];
        if (isset($params['jid']) && $params['jid']) {
            #手动
            $job = DB::table('recruit_job')->where($where)->find($params['jid']);
            $r1  = self::jobMatch($job, $params, $pageSize, $page);

        } else {
//            $r1 = [];
//            # 自动
//            DB::table('recruit_job')->where($where)->orderBy('id')->chunk(100, function ($recruit_jobs, $pageSize, $page) {
//                foreach ($recruit_jobs as $recruit_job) {
//                    $r1[] = self::jobMatch($recruit_job, [], $pageSize, $page);
//                }
//            });
        }

        # 获取 推荐 不合适 感兴趣 面试
        $tj    = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $params['jid']], ["sell", "=", 2]])->count();
        $inap  = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $params['jid']], ["interview", "=", 4]])->count();
        $inter = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $params['jid']], ["interest", "=", 2]])->count();
        $face  = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $params['jid']], ["interview", "=", 2]])->count();
        return ['act' => [], 'auto' => $r1, 'tj' => $tj, 'inap' => $inap, 'inter' => $inter, 'face' => $face];
    }

    /**
     * 匹配构建
     * @param $job
     * @param $params
     */
    private static function jobMatch($job, $params, $pageSize, $page)
    {

        # 开始匹配 薪资 学历 城市 经验 职位类型 工作类型【社 校 实】
        // $salary1              = $job->salary1;
        // $salary2              = $job->salary2;
        // $work_city            = $job->city;
        // $position_category_id = $job->position_category_child_id;
        // $job_type             = $job->job_type;
        // $work_exp             = $job->work_exp;
        // $education            = $job->education;

        $salary1              = "";
        $salary2              = "";
        $work_city            = "";
        $position_category_id = "";
        $job_type             = "";
        $work_exp             = "";
        $education            = "";

        if ($salary1) {
            $where[] = ["salary1", ">=", $salary1];
        }
        if ($salary2) {
            $where[] = ["salary2", "<=", $salary2];
        }

        if ($params && count($params) > 0) {
            if (isset($params['salary']) && $params['salary']) {
                if ($params['salary'] == 1) {
                    $where[] = ["a.salary1", '<=', 3000];
                } elseif ($params['salary'] == 2) {
                    $where[] = ["a.salary1", '>=', 3000];
                    $where[] = ["a.salary2", '<=', 5000];
                } elseif ($params['salary'] == 3) {
                    $where[] = ["a.salary1", '>=', 5000];
                    $where[] = ["a.salary2", '<=', 8000];
                } elseif ($params['salary'] == 4) {
                    $where[] = ["a.salary1", '>=', 8000];
                    $where[] = ["a.salary2", '<=', 10000];
                } elseif ($params['salary'] == 5) {
                    $where[] = ["a.salary1", '>=', 10000];
                    $where[] = ["a.salary2", '<=', 15000];
                } elseif ($params['salary'] == 6) {
                    $where[] = ["a.salary1", '>=', 15000];
                    $where[] = ["a.salary2", '<=', 20000];
                } elseif ($params['salary'] == 7) {
                    $where[] = ["a.salary1", '>=', 20000];
                    $where[] = ["a.salary2", '<=', 30000];
                } elseif ($params['salary'] == 8) {
                    $where[] = ["a.salary1", '>=', 30000];
                    $where[] = ["a.salary2", '<=', 50000];
                } elseif ($params['salary'] == 9) {
                    $where[] = ["a.salary1", '>=', 50000];
                    $where[] = ["a.salary2", '<=', 100000];
                } elseif ($params['salary'] == 10) {
                    $where[] = ["a.salary2", '>=', 100000];
                }
            }

            $position_category_id = $params['position_category_id'] ?? '';
            $job_type             = $params['job_type'] ?? '';
            $education            = $params['education'] ?? '';
            $work_city            = $params['work_city'] ?? '';
            $work_exp             = $params['work_exp'] ?? '';
        }

        if ($position_category_id) {
            $where[] = ["a.position_category_id", "=", $position_category_id];
        }
        if ($job_type) {
            $where[] = ["a.job_type", "=", $job_type];
        }

        if ($work_city) {
            $where[] = ["a.work_city", "=", $work_city];
        }
        $where[] = ["a.status", '=', Status::REGULAR];
        $where[] = ["a.is_deleted", '=', Status::NOT_DELETE];

        if ($work_exp == 2) {
            $where[] = ["a.work_year", "<", 1];
        } elseif ($work_exp == 3) {
            $where[] = ["a.work_year", ">=", 1];
            $where[] = ["a.work_year", "<=", 3];
        } elseif ($work_exp == 4) {
            $where[] = ["a.work_year", ">=", 3];
            $where[] = ["a.work_year", "<=", 5];
        } elseif ($work_exp == 5) {
            $where[] = ["a.work_year", ">=", 5];
            $where[] = ["a.work_year", "<=", 10];
        } elseif ($work_exp == 6) {
            $where[] = ["a.work_year", ">=", 10];
        }

        $whereIn = [];
        if ($education && $education != 1) {
            $whereIn = [$education];
        }

        $info = DB::table('recruit_notes_intention as a')
            ->join('recruit_notes as b', function ($join) {
                $join->on("a.mobile", "=", "b.mobile");
                $join->on("a.job_notes_id", "=", "b.id");
                $join->where("b.status", '=', Status::REGULAR);
                $join->where("b.is_deleted", '=', Status::NOT_DELETE);
            })
            ->distinct("b.mobile")
            ->where($where)
            ->when($whereIn, function ($query, $whereIn) {
                $query->whereIn("a.education", $whereIn);
            })
            ->select(["b.*"])
            ->offset($pageSize * ($page - 1))
            ->limit($pageSize)
            ->get();

        $count = self::getAutoMatchCount($where,$whereIn);

        if (!$info->isEmpty()) {
            $dd = self::buildNoteInfo($info, []);
            return ["data"=>$dd,"total"=>$count];
        }
        return [];
    }


    private static function getAutoMatchCount($where, $whereIn)
    {
        return DB::table('recruit_notes_intention as a')
            ->join('recruit_notes as b', function ($join) {
                $join->on("a.mobile", "=", "b.mobile");
                $join->on("a.job_notes_id", "=", "b.id");
                $join->where("b.status", '=', Status::REGULAR);
                $join->where("b.is_deleted", '=', Status::NOT_DELETE);
            })
            ->distinct("b.mobile")
            ->where($where)
            ->when($whereIn, function ($query, $whereIn) {
                $query->whereIn("a.education", $whereIn);
            })
            ->count();
    }
    /**
     * 匹配结果
     * @param $id
     * @return array
     * 状态 1正常，2邀面试 3已查看【已推荐】 4不合适  8感兴趣 10全部 10全部
     */
    public static function getMateResJob($id, $interview)
    {
        $where = [["a.job_id", '=', $id], ["a.type", '=', 2]];

        if (in_array($interview, [2, 4])) {
            $where[] = ["a.interview", '=', $interview];
        } elseif ($interview == 3) {
            $where[] = ["a.sell", '=', 2];
        } elseif ($interview == 8) {
            $where[] = ["a.interest", '=', 2];
        }

        $data1 = DB::table('recruit_job_notes_auth as a')
            ->leftJoin('recruit_notes as c', function ($join) {
                $join->on("c.mobile", "=", "a.mobile");
            })->select(["c.*", "a.job_id as jid", "a.id as job_notes_id"])
            ->where($where)
            ->get();

        # 自动
        //        $rdInfo  = Redis::HgetAll("business_Viewed_" . $id);
        //        $mobiles = Redis::hKeys("business_Viewed_" . $id);
        //        $data2   = DB::table('recruit_notes as a')
        //            ->whereIn('a.mobile', $mobiles)
        //            ->get();
        //
        $r1 = self::buildNoteInfo($data1, []);
        //        $r2 = self::buildNoteInfo($data2, $rdInfo);

        # 获取 推荐 不合适 感兴趣 面试
        $tj    = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $id], ["sell", "=", 2]])->count();
        $inap  = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $id], ["interview", "=", 4]])->count();
        $inter = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $id], ["interest", "=", 2]])->count();
        $face  = DB::table('recruit_job_notes_auth')->where([["job_id", "=", $id], ["interview", "=", 2]])->count();
        return ['act' => [], 'auto' => $r1, 'tj' => $tj, 'inap' => $inap, 'inter' => $inter, 'face' => $face];
    }


    /**
     * 构建匹配结果数据
     * @param $data
     * @param array $rdInfo
     * @return mixed
     */
    private
    static function buildNoteInfo(
        $data, $rdInfo = []
    ) {
        # 获取用户意向
        foreach ($data as $datum) {
            if ($rdInfo) {
                if (isset($rdInfo[$datum->mobile])) {
                    $datum->viewed = $rdInfo[$datum->mobile];
                }
            }
            $intion = DB::table("recruit_notes_intention")
                ->select(["position_category_id", "job_type", "education", "salary2", "salary1", "work_year", "work_city"])
                ->where(
                    [
                        ["mobile", "=", $datum->mobile],
                        ["status", "=", Status::REGULAR],
                        ["is_deleted", "=", Status::NOT_DELETE],
                    ])->get();

            $datum->intention = "";
            $education        = '';
            if (!$intion->isEmpty()) {
                foreach ($intion as $item) {
                    $education_info = explode(',', $item->education);
                    rsort($education_info);
                    $city_name           = DB::table('recruit_city')->select(["name"])->where("id", $item->work_city)
                        ->first();
                    $item->city_name     = $city_name ? $city_name->name : '';
                    $item->job_type_info = Status::JOB_TYPE[$item->job_type];
                    $education           = $education_info[0] ? Status::EDUCATION[$education_info[0]] : '';
                }

                $datum->intention = $intion;
            }
            $datum->education = $education ?: '';

            # 获取头像
            $datum->path = $datum->head_img ? self::GetUserHeard($datum->head_img) : "";
        }
        return $data;
    }

    /**
     * @param $data
     * @return mixed
     */
    private
    static function getDataInfo(
        $data
    ) {
        foreach ($data as $datum) {
            $area_name        = DB::table('recruit_city')->select("name")->where("id", $datum->area)->first();
            $city_name        = DB::table('recruit_city')->select(["parentid", "name"])->where("id", $datum->city)
                ->first();
            $datum->area_name = $area_name ? $area_name->name : '';
            $datum->city_name = $city_name ? $city_name->name : '';

            $datum->work_exp_info  = Status::WORK_EXP[$datum->work_exp];
            $datum->job_type_info  = Status::JOB_TYPE[$datum->job_type];
            $datum->education_info = Status::EDUCATION[$datum->education];
            $datum->hot_info       = $datum->hot == 1 ? '否' : '是';
            $datum->welfare        = explode(',', $datum->welfare);
        }
        return $data;
    }


    /**
     * 修改匹配结果状态
     * @param $jid
     * @param $type
     * @param $mobile
     * @param $reason
     * @param $job_notes_auth_id
     * @param $annex
     * @param $noteId
     * @return array
     * @throws \Exception
     */
    public
    static function setMateResJobSt(
        $jid, $type, $mobile, $reason, $job_notes_auth_id, $annex, $noteId
    ) {
        $where    = [
            ["job_id", '=', $jid], ["mobile", '=', $mobile],
            ["status", '=', Status::REGULAR], ["is_deleted", '=', Status::NOT_DELETE]
        ];
        $noteInfo = DB::table('recruit_notes')->where([["id", "=", $noteId], ["mobile", "=", $mobile]])->first();
        if (!$noteInfo) {
            return ["status" => Status::ERROR, "msg" => "用户在线简历信息有误！"];
        }
        $info = DB::table('recruit_job_notes_auth')->where($where)->first();

        if ($info && !$job_notes_auth_id) {
            $job_notes_auth_id = $info->id;
        }
        $upData['interview']  = $type;
        $upData['updated_at'] = time();
        $insRec['source']     = 2;
        $insRec['interview']  = $type;
        $insRec['created_at'] = time();
        if ($type == 6) {
            if ($job_notes_auth_id) {
                $info->interest == 1 ? $upData['interest'] = 2 : $upData['interest'] = 1;
                if ($upData['interest'] == 2) {
                    $insRec['interview']       = 8;
                    $upData['interest_reason'] = $reason;
                } else {
                    $insRec['interview'] = 9;
                }
                unset($upData['interview']);

            } else {
                # 第一次 设置
                $upData['interest']        = 2;
                $insRec['interview']       = 8;
                $upData['interest_reason'] = $reason;
            }


        } elseif ($type == 4) {
            if ($job_notes_auth_id) {
                $info->interview == $type ? $upData['interview'] = 3 : $upData['interview'] = 4;
                if ($upData['interview'] == 4) {
                    $upData['reason'] = $reason;
                } else {
                    $insRec['interview'] = 10;
                }
            } else {
                # 第一次 设置
                $upData['interview'] = $type;
                $upData['reason']    = $reason;
            }

        } elseif ($type == 5) {
            unset($upData['interview']);

            # 如果是第一次就发邮件
            if (!$job_notes_auth_id) {
                # 第一次 设置
                $upData['sell'] = $type;

            } else {
                $upData['sell'] = $info->sell == 1 ? $upData['sell'] = 2 : $upData['sell'] = 1;
            }
            # 丢进队列
            //            App\Jobs\SendEmail::dispatch(["noteId" => $noteId, "source" => 1, "annex" => $annex, "jid" => $jid])
            //                ->onConnection('redis');
            // return ["status" => Status::SUCCESS, "msg" => ""];
            # 生成PDF 并发送邮件
            $r = self::createPdfSendEmail($noteId, 1, $jid);
            if ($r['status'] == Status::ERROR) {
                return ["status" => Status::ERROR, "msg" => $r['msg']];
            }
        }

        # 却一个删除 如果任何状态都没了 是否删除

        $connection = DB::connection('mysql');

        $connection->beginTransaction();
        try {
            if (!$job_notes_auth_id && !$info) {
                # 新增
                $upData['mobile']     = $mobile;
                $upData['job_id']     = $jid;
                $upData['type']       = 2;
                $upData['created_at'] = time();
                $job_notes_auth_id    = DB::table('recruit_job_notes_auth')->insertGetId($upData);
            }
            $insRec['job_notes_id'] = $job_notes_auth_id;

            # 修改状态
            DB::table('recruit_job_notes_auth')->where($where)->update($upData);

            # 新增记录
            DB::table('recruit_job_notes_record')->insert($insRec);

            $connection->commit();
            return ["status" => Status::SUCCESS, "msg" => ""];

        } catch (\Exception $exception) {
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }

    }


    /**
     * 获取用户详情
     * @param $mobile
     * @param $id
     * @return mixed
     */
    public static function getNotesDtByMobile($mobile, $id)
    {
        $field = [
            "id", "sex", "user_name", "head_img", "work_st", "weChat", "email", "mobile",
            "birth", "work_date", "adv"
        ];
        if ($id) {
            $nt = Note::select($field)->find($id);
        } else {
            $where = [
                ['mobile', "=", $mobile],
                ['status', "=", Status::REGULAR],
                ['is_deleted', '=', Status::NOT_DELETE]
            ];
            $nt    = Note::where($where)->select($field)->first();
        }
        if (!$nt) {
            return [];
        }

        $nt->work_exp_alias = $nt->project_exp_alias = [];

        if ($nt->work_exp) {
            $work_exp_alias = $project_exp_alias = [];
            foreach ($nt->work_exp as $item) {
                if ($item["tp"] == 1) {
                    $work_exp_alias[] = $item;
                } else {
                    $project_exp_alias[] = $item;
                }
            }
            $nt->work_exp_alias    = $work_exp_alias;
            $nt->project_exp_alias = $project_exp_alias;
            unset($nt->work_exp);
        }

        if ($nt->notes_intention) {
            $nt->notes_intention;
        }
        if ($nt->educational_back) {
            $nt->educational_back;
        }
        $nt->user_header = $nt->annex_path = '';

        if ($nt) {
            $nt->user_header = $nt["head_img"] ? self::GetUserHeard($nt["head_img"]) : "";

            $nt->annex_path = "";
            $nt->annex = [];
            $tmp            = self::GetAnnex($mobile);
            if ($tmp && count($tmp) > 0) {
                $nt->annex      = [["id" => $tmp["id"], "name" => $tmp["name"], "url" => $tmp["path"]]];
                $nt->annex_path = $tmp["path"];
            }
        }
        return self::buildNoteOtherInfo($nt);
    }


    /**
     * @param $data
     * @return mixed
     */
    public
    static function buildNoteOtherInfo(
        $data
    ) {
        foreach ($data->notes_intention as $item) {
            $city_name        = DB::table('recruit_city')->select(["parentid", "name"])->where("id", $item->work_city)
                ->first();
            $positionCategory = DB::table('recruit_position_category')->where("id", $item->position_category_id)
                ->select("name")->first();

            $item->city_info              = $city_name ? $city_name->name : '';
            $item->job_type_info          = Status::JOB_TYPE[$item->job_type];
            $item->position_category_info = $positionCategory ? $positionCategory->name : '';
        }

        foreach ($data->educational_back as $itembk) {
            $itembk->education_info = Status::EDUCATION[$itembk->education];
        }

        return $data;
    }


    /**
     * 面试
     * @param $params
     * @return mixed
     */
    public
    static function setInterview(
        $params
    ) {
        $jobNote = DB::table('recruit_job_notes_auth')->where([["id", "=", $params['note_id']], ["mobile", "=", $params['mobile']]])->first();
        $job     = DB::table('recruit_job')->find($params['job_id']);

        $params['date'] = strtotime($params['date']);

        if (!$job) {
            return ['status' => Status::ERROR, 'msg' => '招聘信息有误'];
        }
        $old = DB::table('recruit_job_interview')->where(
            [
                "status"       => Status::REGULAR,
                "is_deleted"   => Status::NOT_DELETE,
                "job_id"       => $params['job_id'],
                "job_notes_id" => $params['note_id'],
            ])->first();

        if ($old) {
            return ['status' => Status::SUCCESS, 'msg' => '已邀请面试'];
        }

        $connection = DB::connection('mysql');

        $connection->beginTransaction();
        try {
            if (!$jobNote) {
                # 新增
                $upData['mobile']     = $params['mobile'];
                $upData['job_id']     = $params['job_id'];
                $upData['type']       = 2;
                $upData['interview']  = 2;
                $upData['created_at'] = time();
                $job_notes_auth_id    = DB::table('recruit_job_notes_auth')->insertGetId($upData);
            } else {
                $job_notes_auth_id = $jobNote->id;

                # 修改状态
                DB::table('recruit_job_notes_auth')->where([["id", "=", $params['note_id']], ["mobile", "=", $params['mobile']]])
                    ->update(["interview" => 2, "updated_at" => time()]);
            }

            $interviewData["job_id"]        = $params["job_id"];
            $interviewData["job_notes_id"]  = $params["note_id"];
            $interviewData["address"]       = $params["address"];
            $interviewData["date"]          = $params["date"];
            $interviewData["link_username"] = $params["link_username"];
            $interviewData["link_mobile"]   = $params["link_mobile"];
            if (isset($params["remark"]) && $params["remark"]) {
                $interviewData["remark"] = $params["remark"];
            }
            $interviewData['created_at'] = time();

            $r = DB::table('recruit_job_interview')->insert($interviewData);


            # 新增记录
            $insRec['source']       = 2;
            $insRec['interview']    = 2;
            $insRec['job_notes_id'] = $job_notes_auth_id;
            $insRec['created_at']   = time();
            DB::table('recruit_job_notes_record')->insert($insRec);

            $connection->commit();

            return ['status' => $r ? Status::SUCCESS : Status::ERROR, 'msg' => $r ? "邀请成功" : "操作异常"];
        } catch (\Exception $exception) {
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }
    }


    /**
     * @param $noteId
     * @param int $source
     * @param string $jid
     * @return array
     */
    public
    static function createPdfSendEmail(
        $noteId, $source = 1, $jid = ''
    ) {
        $field = [
            "id", "user_name", "head_img", "work_st", "weChat", "email", "mobile",
            "birth", "work_date", "adv", "work_year"
        ];

        # 获取用户信息
        $recruitNotes = Note::where("id", $noteId)
            ->select($field)
            ->first();

        if (!$recruitNotes) {
            return ["status" => Status::ERROR, "msg" => "用户信息有误"];
        }

        $resources = DB::table('recruit_notes_middle as a')
            ->join("recruit_resources as b", "a.res_id", "=", "b.id")
            ->where( [
                'a.mobile'     =>  $recruitNotes->mobile,
                'a.status'     => Status::REGULAR,
                'a.is_deleted' => Status::NOT_DELETE
            ])
            ->select("path")
            ->first();

        if($source == 1) {
            # 职位信息
            $recruit_job = DB::table('recruit_job')
                ->select(["city", "email", "release", "position_custom_name"])
                ->find($jid);

            if (!$recruit_job->city || !$recruit_job->email) {
                return ["status" => Status::ERROR, "msg" => "用户投递职位所在城市信息｜邮箱有误"];
            }

            # 获取需要信息
            $jobInfo['date']                 = date('Y-m-d H:i:s');
            $jobInfo['link']                 = env("JOB_HOST");
            $jobInfo['release']              = $recruit_job->release;
            $jobInfo['user_name']            = $recruitNotes->user_name;
            $jobInfo['position_custom_name'] = $recruit_job->position_custom_name;
            $jobInfo['user']                 = ['email' => $recruit_job->email];
            $dt                              = Helper::timediff(time(), $recruitNotes->birth);
            $yearsDiff                       = ceil($dt["day"] / 365);
            $jobInfo['work_year']            = $recruitNotes->work_year;
            //            $jobInfo['university_name']      = $educationalBack->university_name;
            //            $jobInfo['speciality']           = $educationalBack->speciality;
            //            $jobInfo['education']            = $educationalBack->education ?
            //                Status::EDUCATION[$educationalBack->education] : '';
            //            $jobInfo['job_first']            = $jobFirst->business_name;
        }

        # 推送附件
        if ($resources) {
            $jobInfo['path'] = $resources->path;

            if ($source == 2) {
                $downloadUrl = Helper::buildQiNiuUrl($jobInfo['path']);

                // 本地保存路径和文件名
                $filePath = 'file/pdf/';
                $fileName = rand(1000, 9999) . time() . ".pdf";

                # 保存 PDF 到指定路径
                if (!is_dir(storage_path($filePath))) {
                   File::makeDirectory(storage_path($filePath), 0777, true);
                }
                // 下载文件并保存
                Storage::disk('pdf')->put($fileName, file_get_contents($downloadUrl));
                // 返回下载响应
                return response()->download(storage_path($filePath . $fileName));

            }else {
                self::sendPdfEmailAnnex($jobInfo);

                return ["status" => Status::SUCCESS, "msg" => ""];
            }
        } else {
            if ($recruitNotes->work_exp->isEmpty() || $recruitNotes->notes_intention->isEmpty() ||
                $recruitNotes->educational_back->isEmpty()) {
                return ["status" => Status::ERROR, "msg" => "附件简历不存在，无用户在线工作经验等信息！"];
            }

            $recruitNotes->work_exp;
            $recruitNotes->notes_intention;
            $recruitNotes->educational_back;

            // 创建 TCPDF 实例
            $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8');

            // 设置文档信息
            $pdf->SetCreator('移知招聘');
            $pdf->SetAuthor('移知招聘');
            $pdf->SetTitle('移知招聘');
            $pdf->SetSubject('移知招聘');
            $pdf->SetKeywords('TCPDF, PDF, PHP');

            // 设置页眉和页脚信息
            //        $pdf->SetHeaderData('tcpdf_logo.jpg', 30, 'job.eeeknow.com/recruit/pc/', '学会偷懒，并懒出效率！', [0, 64, 255], [0, 64, 128]);
            //        $pdf->setFooterData([0, 64, 0], [0, 64, 128]);

            // 设置页眉和页脚字体
            $pdf->setHeaderFont(['stsongstdlight', '', '10']);
            $pdf->setFooterFont(['helvetica', '', '8']);

            // 设置默认等宽字体
            $pdf->SetDefaultMonospacedFont('courier');

            // 设置间距
            $pdf->SetMargins(15, 6, 15); //页面间隔
            $pdf->SetHeaderMargin(5);    //页眉top间隔
            $pdf->SetFooterMargin(10);   //页脚bottom间隔

            // 设置分页
            $pdf->SetAutoPageBreak(true, 10);

            // set default font subsetting mode
            $pdf->setFontSubsetting(true);

            //设置字体 stsongstdlight支持中文
            $pdf->SetFont('stsongstdlight', '', 10);

            $pdf->setPrintHeader(false);
            # 页尾
            //        $pdf->setPrintFooter(false);
            // 设置字体间距
            $pdf->SetFontSpacing(0.3);

            $sex = $recruitNotes->sex == 1 ? '男' : '女';

            $html = '<html><body>';
            $html .= '<div style="text-align:center;font-size: 22px;line-height: 1.5">' .
                $recruitNotes->user_name;
            $html .= '<div style=" font-size: 10px;">' . $sex .
                ' | 年龄：' .
                $yearsDiff . ' | ' . $recruitNotes->mobile . '</div>';

            $intention = '';

            foreach ($recruitNotes->notes_intention as $datum) {
                if ($source == 1 && $datum->work_city == $recruit_job->city) {
                    $city_name = DB::table('recruit_city')->select(["name"])->where("id", $datum->work_city)
                        ->first();
                    $city_name = $city_name ? $city_name->name : '';

                    $position_category      = DB::table('recruit_position_category')->select(["name"])->where("id", $datum->position_category_id)
                        ->first();
                    $position_category_name = $position_category ? $position_category->name : '';

                    $intention .= '<div style="font-size: 10px;line-height: 0.5;">' . $datum->work_year .
                        '年工作经验 | 求职意向：' .
                        $position_category_name . ' | ' . $recruitNotes->mobile . ' | 期望薪资：' . $datum->salary1 / 1000 . ' k -' .
                        $datum->salary2 / 1000 .
                        ' k |  期望城市：' . $city_name . '</div>';
                }
                continue;
            }


            $html .= $intention . '<div style="text-align: left;"><span style="font-size: 16px;">个人优势</span><hr>';
            $html .= '<div style="font-size: 12px;line-height: 1.5">' . $recruitNotes->adv . '</div>';
            $html .= '</div>';

            if ($recruitNotes->work_exp) {
                $expHl = '<div style="text-align: left;"><span style="font-size: 16px;">工作经验</span><hr>';
                foreach ($recruitNotes->work_exp as $k1 => $exp) {
                    if ($exp->tp == 1) {
                        $expHl .= '<div style="font-size: 12px;">';
                        $expHl .= '<span>' . $exp->business_name . '&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;' . $exp->position_name .
                            ' &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;' . date('Y.m.d', $exp->work_date_st) .
                            ' - ' . date('Y.m.d', $exp->work_date_ed) . '</span>';
                        $expHl .= '<div>' . $exp->work_exp . '</div>';
                        $expHl .= '</div>';
                    }
                }
                $expHl .= '</div>';
                $html  .= $expHl;
            }

            if ($recruitNotes->work_exp) {
                $expHl2 = '<div style="font-size: 16px;text-align: left;"><span>项目经历</span><hr>';
                foreach ($recruitNotes->work_exp as $expw) {
                    if ($expw->tp == 2) {
                        $expHl2 .= '<div style="font-size: 12px;">';
                        $expHl2 .= '<span>' . $expw->business_name . '&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;' . $expw->position_name .
                            ' &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; ' . date('Y.m.d', $expw->work_date_st) .
                            ' - ' . date('Y.m.d', $expw->work_date_ed) . '</span>';

                        $expHl2 .= '<div>' . $expw->work_exp . '</div>';
                        $expHl2 .= '</div>';
                    }
                }
                $expHl2 .= '</div>';
                $html   .= $expHl2;
            }

            if ($recruitNotes->educational_back) {
                $eduHl = '<div style="font-size: 16px;text-align: left;"><span>教育背景</span><hr>';
                foreach ($recruitNotes->educational_back as $edu) {
                    $education = Status::EDUCATION[$edu->education];
                    $dd        = $edu->university_name . '&nbsp; &nbsp; &nbsp; &nbsp; ' . $education . '&nbsp; &nbsp; &nbsp; &nbsp; ' . $edu->speciality;
                    $eduHl     .= '<div style="font-size: 12px;">' . $dd . '</div>';
                }
                $eduHl .= '</div>';
                $html  .= $eduHl . '</div></body></html>';
            }

            $pdf->AddPage();
            $pdf->writeHTML($html, true, false, true, false, '');

            if ($source == 2) {
                $pdfName = rand(1000, 9999) . $recruitNotes->user_name;
                # 保存 PDF 到指定路径
                if (!is_dir(storage_path('file/pdf'))) {
                    File::makeDirectory(storage_path('file/pdf'), 0777, true);
                }

                # PDF输出的方式。I，默认值，在浏览器中打开；D，点击下载按钮， PDF文件会被下载下来；F，文件会被保存在服务器中；S，PDF会以字符串形式输出；E：PDF以邮件的附件输出。
                $path = storage_path('file/pdf/' . $pdfName . '.pdf');
                $pdf->Output($path, 'D');
            } else {
                $jobInfo['path'] = $pdf->Output('', 'S');
                self::sendPdfEmail($jobInfo);
            }

            return ["status" => Status::SUCCESS, "msg" => ""];
        }


        //        $field = [
        //            "id", "user_name", "head_img", "work_st", "weChat", "email", "mobile",
        //            "birth", "work_date", "adv"
        //        ];
        //        if ($source == 1) {

        # 获取用户信息
        //            $recruitNotes = Note::where("id", $noteId)
        //                ->first();
        //
        //            if (!$recruitNotes) {
        //                return ["status" => Status::ERROR, "msg" => "用户信息有误"];
        //            }

        # 获取用户教育信息
        //            $educationalBack = DB::table('recruit_educational_back')
        //                ->where("mobile", $recruitNotes->mobile)
        //                ->select(["university_name", "speciality", "education"])
        //                ->first();
        //
        //            if (!$educationalBack) {
        //                return ["status" => Status::ERROR, "msg" => "用户教育信息有误"];
        //            }


        # 获取第一次工作经历
        //            $jobFirst = DB::table('recruit_work_exp')
        //                ->where([
        //                    ['status', "=", Status::REGULAR],
        //                    ['is_deleted', '=', Status::NOT_DELETE],
        //                    ["mobile", "=", $recruitNotes->mobile],
        //                    ["tp", "=", 1]
        //                ])
        //                ->orderBy("work_date_st", "asc")
        //                ->select("business_name")
        //                ->first();
        //
        //            if (!$jobFirst) {
        //                return ["status" => Status::ERROR, "msg" => "用户工作经历有误"];
        //            }

        # 获取需要信息
        //            $jobInfo['date']                 = date('Y-m-d H:i:s');
        //            $jobInfo['link']                 = env("JOB_HOST");
        //            $jobInfo['release']              = $recruit_job->release;
        //            $jobInfo['user_name']            = $recruitNotes->user_name;
        //            $jobInfo['university_name']      = $educationalBack->university_name;
        //            $jobInfo['speciality']           = $educationalBack->speciality;
        //            $jobInfo['education']            = $educationalBack->education ?
        //                Status::EDUCATION[$educationalBack->education] : '';
        //            $jobInfo['position_custom_name'] = $recruit_job->position_custom_name;
        //            $jobInfo['user']                 = ['email' => $recruit_job->email];
        //            $jobInfo['job_first']            = $jobFirst->business_name;
        //
        //
        //            $dt                   = Helper::timediff(time(), $recruitNotes->birth);
        //            $yearsDiff            = ceil($dt["day"] / 365);
        //            $jobInfo['work_year'] = $recruitNotes->work_year;

        # 直接推送附件
        //            if ($annex == 2) {
        //                $resources = DB::table('recruit_notes_middle as a')
        //                    ->join("recruit_resources as b", "a.res_id", "=", "b.id")
        //                    ->where("mobile", $recruitNotes->mobile)
        //                    ->select("path")
        //                    ->first();
        //
        //                if (!$resources) {
        //                    return ["status" => Status::ERROR, "msg" => "用户附件简历不存在"];
        //                }
        //
        //                $jobInfo['path'] = $resources->path;
        //
        //                self::sendPdfEmailAnnex($jobInfo);
        //
        //                return ["status" => Status::SUCCESS, "msg" => ""];
        //            }

        //        } else {
        # 下载
        # 手动构建简历
        //            $recruitNotes = Note::where(
        //                [['id', "=", $noteId], ['status', "=", Status::REGULAR], ['is_deleted', '=', Status::NOT_DELETE]]
        //            )->select($field)->first();
        //        }


    }

    /**
     * @param $jobInfo
     */
    private static function sendPdfEmail($jobInfo)
    {
        $jobInfo['source'] = 1;
        $PdfEmail          = new App\Mail\PdfEmail($jobInfo);
        $build             = $PdfEmail->build();
        Mail::to($jobInfo['user'])->send($build);
    }

    /**
     * @param $jobInfo
     */
    private static function sendPdfEmailAnnex($jobInfo)
    {
        $downloadUrl       = Helper::buildQiNiuUrl($jobInfo['path']);
        $jobInfo['path']   = $downloadUrl;
        $jobInfo['source'] = 2;
        $PdfEmail          = new App\Mail\PdfEmail($jobInfo);
        $build             = $PdfEmail->build();
        Mail::to($jobInfo['user'])->send($build);
    }

    /**
     * @param $id
     * @throws \Exception
     */
    public
    static function downloadNote(
        $id
    ) {
        self::createPdfSendEmail($id, 2);
    }
}
